import re
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

import gui_util.gui_common as gui_common


def on_edit_window_closing(window: tk.Toplevel) -> None:
    """处理编辑窗口的关闭事件"""
    window.destroy()


class register_window:
    def __init__(self, root, usession):
        self.root = root
        self.usession = usession
        self.edit_window = None

    def sumit_user(self):
        new_name = self.name_entry.get()
        new_password = self.password_entry.get()
        if not new_name or not new_password:
            messagebox.showwarning("警告", "姓名和密码不能为空")
            return
        else:
            self.usession.register_new_user(new_name, new_password)

    def show(self):
        self.edit_window = tk.Toplevel(self.root)
        self.edit_window.title("注册个人信息")
        self.edit_window.protocol(
            "WM_DELETE_WINDOW", lambda: on_edit_window_closing(self.edit_window)
        )
        gui_common.center_window(self.edit_window, 300, 200)
        # 设置网格列权重，使得第二列可以扩展
        self.edit_window.grid_columnconfigure(1, weight=1)
        for i in range(4):  # 设置四行可扩展
            self.edit_window.grid_rowconfigure(i, weight=1)
        # 创建标签和输入框
        tk.Label(self.edit_window, text="ID:").grid(row=0, column=0)
        self.id_entry = tk.Entry(self.edit_window)
        self.id_entry.insert(0, "注册成功后服务器返回")
        self.id_entry.config(state="readonly")  # 设置ID输入框为只读
        self.id_entry.grid(row=0, column=1, sticky="nsew")

        tk.Label(self.edit_window, text="姓名:").grid(row=1, column=0)
        self.name_entry = tk.Entry(self.edit_window)
        self.name_entry.grid(row=1, column=1, sticky="nsew")

        tk.Label(self.edit_window, text="密码:").grid(row=2, column=0)
        self.password_entry = tk.Entry(
            self.edit_window, show="*"
        )  # 密码输入框显示为星号
        self.password_entry.grid(row=2, column=1, sticky="nsew")
        self.submit_button = tk.Button(
            self.edit_window, text="提交", command=self.sumit_user
        )
        self.submit_button.grid(row=3, columnspan=2, sticky="nsew")


class LoginWindow:
    def __init__(self, usession):
        self.root = tk.Tk()
        self.root.title("用户登录")
        self.ip_combobox = None
        self.init_opition = [
            "8.140.193.207:9000",
            "127.0.0.1:9000",
        ]
        self.user_init_opition = [
            "1",
            "2",
        ]
        self.user_id_combobox = None
        self.password_entry = None
        self.login_button = None
        self.usession = usession
        self.register_window = None

    # 主窗口关闭时，设置退出标志

    def on_closing(self):
        print("login window on_closing")
        if not self.usession.is_logged_in:
            if self.usession.is_connected:
                self.usession.stop_event.set()
                # 可能还需要调用thread.join()来等待线程结束，但这会阻塞主窗口关闭，需谨慎使用
                self.root.destroy()  # 假设root是你的Tkinter窗口实例
            else:
                self.root.destroy()
        else:
            self.root.destroy()

    def register_new_user(self):
        user_input = self.ip_combobox.get()
        ip_pattern = (
            r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)"  # IP地址和端口的正则表达式
        )

        match = re.match(ip_pattern, user_input)
        if match:
            host = match.group(1)
            port = int(match.group(2))
        else:
            messagebox.showerror(
                "输入错误", "请输入有效的IP地址和端口号，格式如: 127.0.0.1:12345"
            )
            return
        if not self.usession.is_connected:
            try:
                self.usession.connect(host, port)
                self.usession.start_recv_thread()
                self.register_window = register_window(self.root, self.usession)
                self.register_window.show()
            except ConnectionRefusedError:
                messagebox.showerror(
                    "连接失败", f"连接{user_input}被拒绝，请检查IP和端口。"
                )
        else:
            self.register_window = register_window(self.root, self.usession)
            self.register_window.show()

    def create_tcp_connection(self):
        user_input = self.ip_combobox.get()
        ip_pattern = (
            r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)"  # IP地址和端口的正则表达式
        )

        match = re.match(ip_pattern, user_input)
        if match:
            host = match.group(1)
            port = int(match.group(2))
        else:
            messagebox.showerror(
                "输入错误", "请输入有效的IP地址和端口号，格式如: 127.0.0.1:12345"
            )
            return
        user_id = self.user_id_combobox.get()
        password = self.password_entry.get()
        if (
            user_id == ""
            or password == ""
            or user_id == "输入或者选择用户编号"
            or password == "请输入密码"
        ):
            messagebox.showerror("输入错误", "请输入用户名和密码")
            return
        try:
            self.usession.set_id_pwd(int(user_id), password)
            if self.usession.is_connected == False:
                self.usession.connect(host, port)
                self.usession.start_recv_thread()
                if self.usession.is_logged_in == False:
                    self.usession.login()
            else:
                if self.usession.is_logged_in == False:
                    self.usession.login()
                else:
                    messagebox.showerror(
                        "已经登录", f"{user_id}已经登录 不需要重复登录"
                    )
        except ConnectionRefusedError:
            messagebox.showerror(
                "连接失败", f"连接{user_input}被拒绝，请检查IP和端口。"
            )

    def on_combobox_focusout(self, event):
        """处理 Combobox 内容变化的事件"""
        new_value = self.ip_combobox.get()
        if (
            new_value not in self.init_opition and new_value
        ):  # 确保新值不为空且不在选项中
            ip_pattern = r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d+)"  # IP地址和端口的正则表达式
            match = re.match(ip_pattern, new_value)
            if match:
                self.init_opition.append(new_value)  # 将新值添加到选项列表
                self.ip_combobox["values"] = self.init_opition  # 更新Combobox的选项
                print(f"已将 '{new_value}' 添加到选项列表。")
        else:
            print(f"用户选择了或输入了: {new_value}")

    def on_user_combobox_focusout(self, event):
        """处理 Combobox 内容变化的事件"""
        new_value = self.user_id_combobox.get()
        if (
            new_value not in self.user_init_opition and new_value
        ):  # 确保新值不为空且不在选项中
            if new_value.isdigit():
                self.user_init_opition.append(new_value)  # 将新值添加到选项列表
                self.user_id_combobox["values"] = (
                    self.user_init_opition
                )  # 更新Combobox的选项
                print(f"已将 '{new_value}' 添加到选项列表。")
        else:
            print(f"用户选择了或输入了: {new_value}")

    def pwd_entry_on_focus_in(self, event):
        """当输入框获得焦点时，如果显示的是提示信息，则清空输入框。"""
        if self.password_entry.get() == "请输入密码":
            self.password_entry.delete(0, tk.END)
            self.password_entry.config(foreground="black")  # 将字体颜色改为黑色
            self.password_entry.config(show="*")

    def user_comobox_on_focus_in(self, event):
        """当输入框获得焦点时，如果显示的是提示信息，则清空输入框。"""
        if self.user_id_combobox.get() == "输入或者选择用户编号":
            self.user_id_combobox.delete(0, tk.END)
            self.user_id_combobox.config(foreground="black")  # 将字体颜色改为黑色

    def show(self):
        gui_common.center_window(self.root, 300, 200)
        self.root.resizable(False, False)

        self.root.grid_columnconfigure(1, weight=1)
        for i in range(4):  # 设置四行可扩展
            self.root.grid_rowconfigure(i, weight=1)
        # 创建标签和输入框
        tk.Label(self.root, text="服务地址:").grid(row=0, column=0, padx=5, pady=5)
        # 初始化 Combobox

        self.ip_combobox = ttk.Combobox(self.root, values=self.init_opition)
        self.ip_combobox.set("127.0.0.1:9000")
        self.ip_combobox.grid(row=0, column=1, padx=5, pady=5)
        # 绑定文本变化的事件，监听用户输入
        self.ip_combobox.bind("<FocusOut>", self.on_combobox_focusout)

        tk.Label(self.root, text="用户ID:").grid(row=1, column=0, padx=5, pady=5)
        self.user_id_combobox = ttk.Combobox(self.root, values=self.user_init_opition)
        # 设置初始值为提示信息，并设置字体颜色为灰色
        placeholder_text = "输入或者选择用户编号"
        self.user_id_combobox.set(placeholder_text)
        user_combobox_style = ttk.Style()
        user_combobox_style.configure(
            "TCombobox", fieldbackground=self.root.cget("bg"), foreground="gray"
        )  # 设置背景和前景色
        self.user_id_combobox.configure(style="TCombobox")
        self.user_id_combobox.grid(row=1, column=1, padx=5, pady=5)
        # 绑定文本变化的事件，监听用户输入
        self.user_id_combobox.bind("<FocusOut>", self.on_user_combobox_focusout)
        self.user_id_combobox.bind("<FocusIn>", self.user_comobox_on_focus_in)

        tk.Label(self.root, text="用户密码:").grid(row=2, column=0, padx=5, pady=5)
        # 创建密码输入框
        self.password_entry = ttk.Entry(self.root)  # 'show="*"’使得输入的内容显示为星号
        self.password_entry.grid(row=2, column=1, padx=5, pady=5)
        self.password_entry.insert(0, "请输入密码")  # 设置初始提示信息
        self.password_entry.config(foreground="gray")  # 初始提示信息为灰色
        self.password_entry.bind(
            "<FocusIn>", self.pwd_entry_on_focus_in
        )  # 绑定获得焦点时的事件

        self.btn_frame = tk.Frame(self.root)
        self.btn_frame.grid(row=3, columnspan=2, sticky="nsew")

        self.login_button = tk.Button(
            self.btn_frame, text="登录", command=self.create_tcp_connection
        )
        self.login_button.pack(side="left", padx=5, pady=5, fill=tk.BOTH, expand=True)

        self.reigister_btn = tk.Button(
            self.btn_frame, text="注册", command=self.register_new_user
        )
        self.reigister_btn.pack(side="left", padx=5, pady=5, fill=tk.BOTH, expand=True)

        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.mainloop()

    def destroy(self):
        self.root.destroy()
